package com.xcity.game.adventure.model;

import java.util.Collection;
import java.util.Map;

import com.xcity.db.entity.Player;
import com.xcity.game.player.cache.PlayerCacheService;

import gnu.trove.queue.TLongQueue;
import naga.x.App;
import naga.x.util.LRUCache;
import naga.x.util.TLongArrayBlockingQueue;

public class ActionTargetQueue {

	private int capacity;
	// 目标玩家队列
	private TLongQueue queue;
	// 计数器（记录玩家被偷次数+被攻击次数，每天凌晨重置）
	private Map<Long, Byte> counters;
	
	private PlayerCacheService cacheService;
	
	public ActionTargetQueue() {
		this.capacity = 512;
		this.queue = new TLongArrayBlockingQueue(capacity);
		this.counters = new LRUCache<Long, Byte>(capacity << 1);
		this.cacheService = App.getApp().getServiceManager().get(PlayerCacheService.class);
	}
	
	public void clear() {
		counters.clear();
		queue.clear();
	}
	
	public boolean offer(Player player) {
		return offer(player, false);
	}
	
	public boolean offer(Player player, boolean force) {
		return offer(player.getId(), force);
	}
	
	public boolean offer(Long id, boolean force) {
		if (counters.containsKey(id)) {
			if (force) {
				return queue.offer(id);
			}
			return true;
		}
		if (queue.offer(id)) {
			counters.put(id, Byte.valueOf((byte) 0));
			return true;
		}
		return false;
	}
	
	public boolean offer(Collection<Player> players) {
		for (Player player : players) {
			if (!offer(player)) {
				return false;
			}
		}
		return true;
	}
	
	public Player poll() {
		long id = queue.poll();
		if (id == queue.getNoEntryValue()) {
			return null;
		}
		return cacheService.find(id);
	}
	
	public int size() {
		return queue.size();
	}
	
	public int capacity() {
		return capacity;
	}
	
	public byte getBeTargetCount(Player player) {
		Byte count = counters.get(player.getId());
		return count != null ? count.byteValue() : 0;
	}
	
	public byte countAdd(Player player) {
		Long key = Long.valueOf(player.getId());
		Byte count = counters.get(key);
		count = (byte) (count != null ? count.byteValue() + 1 : 1);
		counters.put(key, count);
		return count.byteValue();
	}
	
}
